<template>
  <el-dialog
    :title="dialogOptions.title"
    :visible.sync="dialogOptions.visible"
    :width="dialogOptions.width"
    :before-close="handleClose"
    :close-on-click-modal="dialogOptions.closeModal"
    :close-on-press-escape="false"
    append-to-body
    :fullscreen="dialogOptions.fullscreen"
  >
    <template v-if="$scopedSlots.default">
      <slot name="default" :options="execList"></slot>
    </template>
    <div slot="footer">
      <slot name="footer" :footer="{ exec, close, pause, start }"></slot>
    </div>
  </el-dialog>
</template>

<script>
import dialogMixin from "../utils/dialog-mixins"
import AsyncTask from "../async"
export default {
  name: "VueAsyncDialog",
  componentName: 'VueAsyncDialog',
  mixins: [dialogMixin],
  props: {
    selectedList: Array,
    action: {
      type: [Function],
      required: true,
    },
    concurrency: {
      type: Number,
      default: 1,
    },
    autoStart: {
      type: Boolean,
      default: false,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "table", // table | custom
    },
  },
  provide() {
    return {
      asyncDialog: this,
    }
  },
  data() {
    return {
      asyncTask: null,
      execList: [],
      show: false
    }
  },
  created() {
    this.$watch(
      () => this.selectedList,
      (list) => {
        this.execList = list
      },
      {
        immediate: true,
        deep: true,
      }
    )
  },
  watch: {
    visible: {
      handler(vis) {
        if(vis) {
          this.showDialog()
        } else {
          this.closeDialog()
        }
      },
      immediate: true
    }
  },
  methods: {
    exec() {
      if (this.asyncTask) {
        this.asyncTask.clear()
      }
      this.asyncTask = new AsyncTask({
        autoStart: this.autoStart,
        concurrency: this.concurrency,
        onIdle: () => {
          this.$emit("success")
          console.log("All tasks completed")
        },
        task: this.action,
        execList: this.execList,
      })
      this.asyncTask.exec()
    },
    pause() {
      if (this.asyncTask) {
        this.asyncTask.pause()
      }
    },
    start() {
      if (this.asyncTask) {
        this.asyncTask.start()
      }
    },
    close() {
      this.closeDialog()
    }
  },
  mounted() {
  }
}
</script>
